package dwz.web.management;


import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.apache.commons.io.FileUtils;
import dwz.business.article.Article;
import dwz.business.article.ArticleServiceMgr;
import dwz.business.article.ArticleStatus;
import dwz.business.menu.Menu;
import dwz.business.menu.MenuLevel;
import dwz.business.menu.MenuServiceMgr;
import dwz.business.menu.MenuStatus;
import dwz.framework.sys.exception.ServiceException;
import dwz.persistence.BaseConditionVO;
import dwz.persistence.beans.WechatArticle;
import dwz.web.BaseController;

@Controller("management.articleController")
@RequestMapping(value="/management/article")
public class ArticleController extends BaseController{
	@Resource
	private ArticleServiceMgr articleMgr;
	@Resource
	private MenuServiceMgr menuMgr;
	public File getImg() {
		return img;
	}


	public void setImg(File img) {
		this.img = img;
	}


	public String getImgFileName() {
		return imgFileName;
	}


	public void setImgFileName(String imgFileName) {
		this.imgFileName = imgFileName;
	}

	private File img;//产品详情产品图片
	private String imgFileName;//产品详情产品名称
		
	@RequestMapping("")
	public String list(BaseConditionVO vo, Model model) {
		//查询所有的二级菜单信息
		vo.setLevel(MenuLevel.SECOND.toString());
		List<Menu> menuList = menuMgr.searchMenu(vo);
		
		
		List<Article> articleList=articleMgr.searchArticle(vo);
		Integer totalCount=articleMgr.searchArticleNum(vo);
		model.addAttribute("articleList", articleList);
		model.addAttribute("totalCount", totalCount);
		model.addAttribute("pageSize", vo.getPageSize());
		model.addAttribute("menuList", menuList);
		return "/management/article/list";
	}
	
	
	@RequestMapping("/add")
	public String add(Model model) {
		//查询所有的二级级菜单信息
		BaseConditionVO vo=new BaseConditionVO();
		vo.setLevel(MenuLevel.SECOND.toString());
		List<Menu> menuList = menuMgr.searchMenu(vo);
		model.addAttribute("menuList", menuList);
		
		return "/management/article/add";
	}
	
	
	@RequestMapping("/edit/{articleId}")
	public String edit(@PathVariable("articleId") int articleId, Model model) {
		Article article = articleMgr.getArticle(articleId);
		model.addAttribute("vo", article);
		
		//查询所有的二级级菜单信息
		BaseConditionVO vo = new BaseConditionVO();
		vo.setLevel(MenuLevel.SECOND.toString());
		List<Menu> menuList = menuMgr.searchMenu(vo);
		model.addAttribute("menuList", menuList);
		return "/management/article/edit";
	}
	

	@RequestMapping(value = "/insert", method = RequestMethod.POST)
	public ModelAndView insert(Article article, @RequestParam MultipartFile[] myfiles, HttpServletRequest request) {
		try {
			
			for (MultipartFile myfile : myfiles) {
				if (myfile.isEmpty()) {
					System.out.println("文件未上传");
				} else {
					System.out.println("文件长度: " + myfile.getSize());
					System.out.println("文件类型: " + myfile.getContentType());
					System.out.println("文件名称: " + myfile.getName());
					System.out.println("文件原名: " + myfile.getOriginalFilename());
					System.out.println("========================================");
					
					//
					java.text.Format format=new SimpleDateFormat("yyyyMMddHHmmssSS");
					String fileName=format.format(new Date())+myfile.getOriginalFilename().substring(myfile.getOriginalFilename().lastIndexOf("."));
					// 如果用的是Tomcat服务器，则文件会上传到\\%TOMCAT_HOME%\\webapps\\YourWebProject\\styles\\upload\\文件夹中
					String realPath = request.getSession().getServletContext().getRealPath("/styles/upload");
					// 这里不必处理IO流关闭的问题，因为FileUtils.copyInputStreamToFile()方法内部会自动把用到的IO流关掉，我是看它的源码才知道的
					FileUtils.copyInputStreamToFile(myfile.getInputStream(),new File(realPath, fileName));
					
					
					String servletName=request.getServerName();
					int servetPort=request.getServerPort();
					String contextPath=request.getContextPath();
					String resPath="http://"+servletName+":"+servetPort+contextPath+"/styles/upload/"+fileName;
					
					//设置上传的图片文件路径
					WechatArticle wechatArticle=article.getWechatArticle();
					wechatArticle.setPicUrl(resPath);
					article.setWechatArticle(wechatArticle);
				}
			}

			
			articleMgr.addArticle(article);
		} catch (ServiceException e) {
			return ajaxDoneError(e.getMessage());
		} catch (IOException e) {
			return ajaxDoneError(e.getMessage());
		}

		return ajaxDoneSuccess(getMessage("msg.operation.success"));
	}
	
	
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public ModelAndView update(Article article,@RequestParam MultipartFile[] myfiles, HttpServletRequest request) {
		
		for (MultipartFile myfile : myfiles) {
			if (myfile.isEmpty()) {
				System.out.println("文件未上传");
			} else {
				java.text.Format format=new SimpleDateFormat("yyyyMMddHHmmssSS");
				String fileName=format.format(new Date())+myfile.getOriginalFilename().substring(myfile.getOriginalFilename().lastIndexOf("."));
				// 如果用的是Tomcat服务器，则文件会上传到\\%TOMCAT_HOME%\\webapps\\YourWebProject\\styles\\upload\\文件夹中
				String realPath = request.getSession().getServletContext().getRealPath("/styles/upload");
				try {
					FileUtils.copyInputStreamToFile(myfile.getInputStream(),new File(realPath, fileName));
				} catch (IOException e) {
					// TODO Auto-generated catch block
					return ajaxDoneError(e.getMessage());
				}
				
				
				String servletName=request.getServerName();
				int servetPort=request.getServerPort();
				String contextPath=request.getContextPath();
				String resPath="http://"+servletName+":"+servetPort+contextPath+"/styles/upload/"+fileName;
				
				//设置上传的图片文件路径
				WechatArticle wechatArticle=article.getWechatArticle();
				wechatArticle.setPicUrl(resPath);
				article.setWechatArticle(wechatArticle);
			}
		}
		
		articleMgr.updateArticle(article);
		return ajaxDoneSuccess(getMessage("msg.operation.success"));
	}
	
	@RequestMapping("/delete/{articleId}")
	public ModelAndView delete(@PathVariable("articleId") int articleId) {
		articleMgr.updateStatus(articleId,ArticleStatus.DELETED.toString());
		return ajaxDoneSuccess(getMessage("msg.operation.success"));
	}
	
	
	@RequestMapping("/active/{articleId}")
	public ModelAndView active(@PathVariable("articleId") int articleId) {
		articleMgr.updateStatus(articleId,ArticleStatus.ACTIVE.toString());
		return ajaxDoneSuccess(getMessage("msg.operation.success"));
	}
	
	@RequestMapping("/inactive/{articleId}")
	public ModelAndView inactive(@PathVariable("articleId") int articleId) {
		articleMgr.updateStatus(articleId,ArticleStatus.INACTIVE.toString());
		return ajaxDoneSuccess(getMessage("msg.operation.success"));
	}
	
	
	
}